<?php
/*
 * @Author: zwx
 * @Date: 2024-06-02 17:59:53
 * @LastEditors: zwx
 * @LastEditTime: 2024-09-02 23:53:17
 * @Description:  获取MongoDB数据库中存输的直播数据 
 */

namespace app\apiadmin\service\statics;

use app\apiadmin\controller\liveManager\LiveStatus;
use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime;
use think\facade\Db;
use MongoDB\Driver;
use MongoDB\Driver\Query;
use function Symfony\Component\String\length;

class LiveUserGetDataService
{

    /** @var MongoDbService */
    private $_mongodb;

    public function __construct($collection)
    {
        $this->_mongodb = MongoDBService::getInstance($collection);
    }

    /**
     * @author: zwx
     * @Description: 获取所有用户在线信息
     * @param {*} $map  筛选条件
     * @param {*} $findName  筛选结果
     * @param {*} $offset  偏移量
     * @param {*} $limit  每页条数
     * @Date: 2024-06-02 18:44:39
     */
    public function pageMap_userinfo($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);
        // dump($data);
        // die;
        return $list;
    }

    public function live_user_info($map, $findName)
    {
        $colletcion = $this->_mongodb->getCollection();

        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }
        return $list;
    }

    public function getYaoqingZhujiao($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;

    }

    public function getYaoqingZhujiao2($map)
    {

        $colletcion = $this->_mongodb->getCollection();

        // 聚合查询的pipeline
        $pipeline = [
            // 第一步：根据live_id过滤文档
            [
                '$match' => $map,
            ],
            //第二步：根据tutor_id和status分组，并计算每个组内的user_id排重数量
            [
                '$group' => [
                    '_id' => [
                        'tutor_id' => '$tutor_id',
                        'tutor_nickname' => '$tutor_nickname'
                    ],
                    // 'uniqueUserIds' => ['$addToSet' => '$user_id'],
                    'tutor_nickname' => ['$first' => '$tutor_nickname'], // 添加tutor_nickname到分组结果中
                    'tutor_id' => ['$first' => '$tutor_id'], // 添加tutor_nickname到分组结果中
                ],
            ],

        ];

        // 执行聚合查询
        $results = $colletcion->aggregate($pipeline);
        $data = [];
        // 遍历查询结果
        foreach ($results as $document) {

            $a = [];
            $a['tutor_nickname'] = $document['tutor_nickname'];
            $a['tutor_id'] = $document['tutor_id'];
            $data['list'][] = $a;
        }

        return $data;

    }


    public function pageMapCount_userinfo($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }

    public function delUserInfo($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }

    public function pldelUserInfo($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateMany($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }
    }


    public function getuser($map)
    {
        $colletcion = $this->_mongodb->getCollection();

        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }






    /**
     * @author: zwx
     * @Description: 获取邀请总览信息
     * @param {*} $map  筛选条件
     * @param {*} $findName  筛选结果
     * @param {*} $offset  偏移量
     * @param {*} $limit  每页条数
     * @Date: 2024-06-02 18:44:39
     */
    public function pageMap_yaoqing($map, $findName, $offset, $limit)
    {

        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }


    public function pageMapCount_yaoqing($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }


    public function delyaoqing($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }

    public function pldelyaoqing($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateMany($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }
    }


    /**
     * @author: zwx
     * @Description: 获取邀请总览信息
     * @param {*} $map  筛选条件
     * @param {*} $findName  筛选结果
     * @param {*} $offset  偏移量
     * @param {*} $limit  每页条数
     * @Date: 2024-06-02 18:44:39
     */
    public function pageMap_pinglun($map, $findName, $offset, $limit)
    {

        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }


    public function pageMapCount_pinglun($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }

    public function delpinglun($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }

    public function pldelpinglun($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateMany($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }
    }


    public function addpinglun($map)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->insertOne($map);

        if ($result->getInsertedCount() === 1) {
            return 1;
        } else {
            return 0;
        }



    }


    public function editpinglun($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }


    public function pageMap_yaoyue($map, $findName, $offset, $limit)
    {

        $colletcion = $this->_mongodb->getCollection();

        // 聚合查询的pipeline
        $pipeline = [
            // 第一步：根据live_id过滤文档
            [
                '$match' => $map,
            ],
            //第二步：根据tutor_id和status分组，并计算每个组内的user_id排重数量
            [
                '$group' => [
                    '_id' => [
                        'tutor_id' => '$tutor_id',
                        'tutor_nickname' => '$tutor_nickname',
                        'status' => '$status',
                    ],
                    'uniqueUserIds' => ['$addToSet' => '$user_id'],
                    'tutorNickname' => ['$first' => '$tutor_nickname'], // 添加tutor_nickname到分组结果中
                ],
            ],
            //第三步：根据tutor_id重新分组，并计算status为1和2时的user_id排重数量
            [
                '$group' => [
                    '_id' => '$_id.tutor_id',
                    'yaoyuenum' => [
                        '$sum' => [
                            '$cond' => [
                                ['$eq' => ['$_id.status', 1]],
                                [
                                    '$size' => '$uniqueUserIds'
                                ],
                                0
                            ]
                        ]
                    ],
                    'daokenum' => [
                        '$sum' => [
                            '$cond' => [
                                ['$eq' => ['$_id.status', 2]],
                                [
                                    '$size' => '$uniqueUserIds'
                                ],
                                0
                            ]
                        ]
                    ],
                    'tutorNickname' => ['$first' => '$tutorNickname'], // 选择一个tutor_nickname作为代表
                ],
            ],
            //第四步：计算比值，但只包括那些daokenum不为零的文档
            [
                '$addFields' => [
                    'yaoyue_daoke_lv' => [
                        '$cond' => [
                            ['$gt' => ['$yaoyuenum', 0]],
                            [
                                '$multiply' => [
                                    [
                                        '$divide' => ['$daokenum', '$yaoyuenum']
                                    ],
                                    100
                                ]
                            ],
                            0
                        ]
                    ],
                ],
            ],

            //第五步：分页
            [
                '$skip' => $offset,
            ],
            [
                '$limit' => $limit,
            ],
        ];

        // 执行聚合查询
        $results = $colletcion->aggregate($pipeline);

        // 遍历查询结果
        foreach ($results as $document) {
            $offset++;
            $a = [];
            $a['id'] = $offset;
            $a['tutor_nickname'] = $document['tutorNickname'];
            $a['tutor_id'] = $document['_id'];
            $a['yaoyuenum'] = $document['yaoyuenum'];
            $a['daokenum'] = $document['daokenum'];
            $a['yaoyue_daoke_lv'] = $document['yaoyue_daoke_lv'];
            $data[] = $a;
        }

        return $data;
    }


    public function pageMapCount_yaoyue($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        // $data = $colletcion->count($map);

        // 聚合查询的pipeline
        $pipeline = [
            // 第一步：根据live_id过滤文档
            [
                '$match' => $map,
            ],
            //第二步：根据tutor_id和status分组，并计算每个组内的user_id排重数量
            [
                '$group' => [
                    '_id' => [
                        'tutor_id' => '$tutor_id',
                        'tutor_nickname' => '$tutor_nickname',
                        'status' => '$status',
                    ],
                    'uniqueUserIds' => ['$addToSet' => '$user_id'],
                    'tutorNickname' => ['$first' => '$tutor_nickname'], // 添加tutor_nickname到分组结果中
                ],
            ],
            //第三步：根据tutor_id重新分组，并计算status为1和2时的user_id排重数量
            [
                '$group' => [
                    '_id' => '$_id.tutor_id',
                    'yaoyuenum' => [
                        '$sum' => [
                            '$cond' => [
                                ['$eq' => ['$_id.status', 1]],
                                [
                                    '$size' => '$uniqueUserIds'
                                ],
                                0
                            ]
                        ]
                    ],
                    'daokenum' => [
                        '$sum' => [
                            '$cond' => [
                                ['$eq' => ['$_id.status', 2]],
                                [
                                    '$size' => '$uniqueUserIds'
                                ],
                                0
                            ]
                        ]
                    ],
                    'tutorNickname' => ['$first' => '$tutorNickname'], // 选择一个tutor_nickname作为代表
                ],
            ],
            //第四步：计算比值，但只包括那些daokenum不为零的文档
            [
                '$addFields' => [
                    'yaoyue_daoke_lv' => [
                        '$cond' => [
                            ['$gt' => ['$yaoyuenum', 0]],
                            [
                                '$multiply' => [
                                    [
                                        '$divide' => ['$daokenum', '$yaoyuenum']
                                    ],
                                    100
                                ]
                            ],
                            0
                        ]
                    ],
                ],
            ]
        ];

        // 执行聚合查询
        $results = $colletcion->aggregate($pipeline);

        $a = 0;
        foreach ($results as $document) {
            $a++;
        }

        return $a;
    }


    public function addOderInfo($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->insertOne($map);
        return $data;
    }

    public function updateOrder($map, $update)
    {
        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }

    }


    public function addEvent($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->insertOne($map);
        return $data;
    }

    public function updateEvent($map, $update)
    {
        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }

    }

    public function pageMap_payorder($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function pageMapCount_payorder($map)
    {

        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }


    public function pageMap_shijian($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function pageMap_shijian2($map, $findName)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $v['id'] = $k + 1;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function live_event($map, $findName)
    {
        $colletcion = $this->_mongodb->getCollection();

        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }
        return $list;
    }

    public function pageMapCount_shijian($map)
    {

        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }


    public function pageMap_jilu($map, $findName)
    {
        $colletcion = $this->_mongodb->getCollection();

        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }
        return $list;
    }

    public function pageMapCount_jilu($map)
    {

        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->find($map);

        $list = array();
        foreach ($data as $k => $v) {
            $list[] = $v;
        }

        $num = count($list[0]['enter_log']);

        return $num;
    }


    public function pageMap_pinglunuser($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function pageMapCount_pinglunuser($map)
    {

        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }



    public function pageMap_guankong($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function pageMapCount_guankong($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }

    public function delguankong($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }

    public function pldelguankong($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateMany($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }
    }

    public function pageMap_yingxiao($map, $findName, $offset, $limit)
    {
        $colletcion = $this->_mongodb->getCollection();
        $options = [
            'projection' => $findName,  //查询结果字段
            'skip' => $offset, // 跳过的记录数
            'limit' => $limit, // 每页记录数
            'sort' => ['_id' => -1], // 可选的排序
        ];

        $data = $colletcion->find($map, $options);

        $list = array();
        foreach ($data as $k => $v) {
            $offset++;
            $v['id'] = $offset;
            $list[] = $v;
        }
        // dump($map);dump($list);die;
        return $list;
    }

    public function pageMapCount_yingxiao($map)
    {
        $colletcion = $this->_mongodb->getCollection();
        $data = $colletcion->count($map);

        return $data;
    }

    public function delyingxiao($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateOne($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }


    }

    public function pldelyingxiao($map, $update)
    {

        $colletcion = $this->_mongodb->getCollection();

        $result = $colletcion->updateMany($map, $update);

        if ($result->getModifiedCount() >= 1) {
            return 1;
        } else {
            return 0;
        }
    }



    public function entertime($param)
    {
        $colletcion = $this->_mongodb->getCollection();


        $id = time();
        $enter_log_item = [
            "start_time" => $param['time'],
            "status" => 1,
            "exit_time" => 0,
            "id" => $id
        ];



        $docWhere = ["live_user_id" => $param['user_id']];
        $oldDoc = $colletcion->findOne($docWhere);
        if (empty($oldDoc)) {

            $data['liveId'] = $param['liveId'];
            $data['live_user_id'] = $param['user_id'];
            $data['online_status'] = 1;
            $data['last_enter_time'] = $param['time'];
            $data['exit_first'] = 0;
            $data['del'] = 0;
            // 不存在 补充用户信息
            $userInfo = LiveUserStaticsService::getUserInfo($param['user_id']);

            // 合并数据,合并用户信息
            $newDoc = array_merge($data, $userInfo);
            $newDoc["enter_log"][] = $enter_log_item;

            $res = $colletcion->insertOne($newDoc);
        } else {



            $res = $colletcion->updateOne($docWhere, [
                '$push' => [
                    "enter_log" => $enter_log_item,
                ],
                '$set' => ['online_status' => 1, 'last_enter_time' => $param['time']]
            ]);



        }



        $result = [
            'live_id' => $param['liveId'],
            'live_user_id' => $param['user_id'],
            'id' => $id,
            'res' => $res
        ];

        return $result;
    }


    public function exittime($param)
    {
        $colletcion = $this->_mongodb->getCollection();

        $data['liveId'] = $param['liveId'];
        $data['live_user_id'] = $param['user_id'];
        $data['online_status'] = 1;
        $data['last_enter_time'] = $param['time'];
        $data['exit_first'] = 0;
        $data['del'] = 0;

        $res = $colletcion->insertOne($data);

        $map['liveId'] = $param['liveId'];
        $map['live_user_id'] = $param['user_id'];

        $result = $colletcion->findOne($map);

        $data = [];

        foreach ($result as $k => $v) {
            foreach ($v['enter_log'] as $k2 => $v2) {
                if ($v2['id'] == $param['id']) {
                    $data[] = [
                        "create_time" => new UTCDateTime(date('Y-m-d H:i:s', time())),
                        "status" => 0,
                        "event_time" => $param['time'],
                        "id" => $v2['id']
                    ];

                    //记录直播观看总时长
                    if (!empty($param['time']) && !empty($v2['time'])) {
                        $liveStatus = new LiveStatus($param['liveId']);
                        $time_diff = $param['time'] - $v2['time'];
                        $liveStatus->set_zong_guankan_shichang($time_diff);

                        //获取直播观看总时长
                        $zongshicahng = $liveStatus->get_zong_guankan_shichang();

                        //获取总人数
                        $zongrenshu = $liveStatus->get_guankan_renshu();

                        //记录平均观看时长
                        if ($zongrenshu) {
                            $liveStatus->set_pingjun_guankan_shichang(number_format($zongshicahng / $zongrenshu, 2));
                        } else {
                            $liveStatus->set_pingjun_guankan_shichang(0);
                        }
                    }

                } else {
                    $data[] = $v2;
                }
            }

        }

        $res = $colletcion->updateOne($map, ['$set' => ['enter_log' => $data, 'exit_first' => 1, "last_exit_time" => $param['time'], "online_status" => 0]]);


        $result = [
            'live_id' => $param['liveId'],
            'live_user_id' => $param['user_id'],
            'id' => $param['id'],
            'res' => $res
        ];

        return $result;
    }

    public function addGongGao($params)
    {


        $colletcion = $this->_mongodb->getCollection();

        $res = $colletcion->insertOne($params);
    }

    public function addBlackBoard($params)
    {


        $colletcion = $this->_mongodb->getCollection();

        $res = $colletcion->insertOne($params);
    }

    /**
     * @param $aggregate
     * @return int
     * Created by chenyawei on 2024/7/17
     * Description:获取用户平均在线时间
     */
    public function getUserOnlineTime($aggregate)
    {
        $data = $this->_mongodb->getCollection()->aggregate($aggregate);
        $averageOnlineTime = null;
        foreach ($data as $document) {
            $averageOnlineTime = $document->averageOnlineTime; // 获取平均值  
            break;
        }
        return $averageOnlineTime ?? 0;
    }


    public function getActiveUserNum()
    {
        $filter = ['del' => 0, 'is_real_msg' => true];
        $data = $this->_mongodb->getCollection()->distinct('live_user_id', $filter);
        return count($data);
    }
}
